package cool.mtc.security.handler.auth.jwt;

import cool.mtc.security.auth.jwt.JwtAuthForm;
import cool.mtc.security.constant.AuthConstant;
import cool.mtc.security.constant.SecurityConstant;
import cool.mtc.security.handler.auth.AuthFailureHandler;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 明河
 */
@Component
public class JwtAuthFailureHandler extends AuthFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) {
        SecurityContextHolder.clearContext();
        this.fail(ex);

        JwtAuthForm form = (JwtAuthForm) request.getAttribute(SecurityConstant.REQUEST_ATTRIBUTE_KEY_AUTH_FORM);
        super.publishAuthFailureEvent(request, form, AuthConstant.AUTH_WAY_JWT, ex.getMessage());
    }
}
